import dayjs from "dayjs"
import Tracker from "./Tracker";
const base = ''
const host = 'cn-chengdu.log.aliyuncs.com';
const project = 'catv2';
const logstore = 'logsv1';
// @ts-ignore
if (process.env.NODE_ENV === 'development') {
    // const base = 'http://127.0.0.1:9678'
    // // @ts-ignore
    // wx.cloud.callContainer = (obj: Iwx.IcallContainer) => {
    //     return uni.request({
    //         url: base + obj.path,
    //         data: obj.data,
    //         // @ts-ignore
    //         method: obj.method,
    //         header: {
    //             ...obj.header,
    //             ['x-wx-unionid']: 'odHkE6RICFTIKJnZIEuk3JEZjBKw',
    //             ['x-wx-openid']: 'o4qSV67inSw8MCMXSdMyAIfi2ISw'
    //         },
    //         success: obj.success,
    //         fail: obj.fail,
    //         complete: obj.complete
    //     })
    // }
}


export interface IpageDate<T> {
    list: T[],
    pagination: {
        page: number,
        size: number,
        total: number
    }
}

export const env = 'prod-5g68x6an4c58cdc7'
export const header = {
    'X-WX-SERVICE': 'catv2serve'
}

let activeRequestsCount = 0;
let loadingTimer: number | null = null;
let isLoadingVisible = false;
let showLoadingTimer: number | null = null;

function showGlobalLoading() {
    activeRequestsCount++;
    console.log(`[Loading] Active requests: ${activeRequestsCount}`);

    // 防抖：避免频繁显示loading
    if (showLoadingTimer) {
        clearTimeout(showLoadingTimer);
    }

    showLoadingTimer = setTimeout(() => {
        if (activeRequestsCount > 0 && !isLoadingVisible) {
            isLoadingVisible = true;
            uni.showLoading({
                title: '加载中',
            });

            // 添加超时机制，15秒后强制隐藏loading
            if (loadingTimer) {
                clearTimeout(loadingTimer);
            }
            loadingTimer = setTimeout(() => {
                console.warn('[Loading] Timeout, force hide');
                forceHideLoading();
            }, 15000);
        }
        showLoadingTimer = null;
    }, 100); // 100ms防抖延迟
}

function hideGlobalLoading() {
    if (activeRequestsCount > 0) {
        activeRequestsCount--;
    }
    console.log(`[Loading] Active requests after hide: ${activeRequestsCount}`);

    if (activeRequestsCount === 0) {
        // 清除所有定时器
        if (loadingTimer) {
            clearTimeout(loadingTimer);
            loadingTimer = null;
        }
        if (showLoadingTimer) {
            clearTimeout(showLoadingTimer);
            showLoadingTimer = null;
        }

        if (isLoadingVisible) {
            isLoadingVisible = false;
            uni.hideLoading();
        }
    }
}

function forceHideLoading() {
    console.log('[Loading] Force hide loading');
    activeRequestsCount = 0;
    isLoadingVisible = false;

    // 清除所有定时器
    if (loadingTimer) {
        clearTimeout(loadingTimer);
        loadingTimer = null;
    }
    if (showLoadingTimer) {
        clearTimeout(showLoadingTimer);
        showLoadingTimer = null;
    }

    uni.hideLoading();
}

export default async function api<T = unknown>(url: string, data?: any) {
    showGlobalLoading();
    return new Promise<T>((res, rej) => {
        const log = new Tracker(host, project, logstore);
        const times = Date.now()
        const user = uni.getStorageSync('user')
        log.push('_url_', url);
        log.push('_userid_', user?.tenant_user_id);
        log.push('_tenantid_', user?.tenantId);
        log.push('_name_', user?.name);
        log.push('_phone_', user?.phone);
        if (data) {
            log.push('_body_', JSON.stringify(data));
        }
        log.push('_type_', 'xiaochengxu')
        wx.cloud.callContainer({
            config: {
                env
            },
            path: url,
            header: {
                ...header
            },
            method: 'POST',
            data,
            success(r) {

                console.log(r)
                if (r.data.code === 1000) {
                    res(r.data.data)
                    return;
                }
                // 改进错误信息处理
                const errorMessage = r.data.message || r.data.msg || '请求失败'
                rej(errorMessage)
            },
            fail(f) {
                console.log(f)
                // 改进网络错误处理
                let errorMessage = '网络请求失败'
                if (f.data?.message) {
                    errorMessage = f.data.message
                } else if (f.data?.msg) {
                    errorMessage = f.data.msg
                } else if (f.errMsg) {
                    errorMessage = f.errMsg
                }
                rej(errorMessage)
            },
            complete(ccc) {
                const time = Date.now() - times
                log.push('_time_', time)
                log.push('_code_', ccc.data?.code)
                log.push('errMsg', ccc.errMsg)
                log.push('statusCode', ccc.statusCode)
                log.logger()
                hideGlobalLoading();
            }
        })
    })
}


export async function apiget<T = unknown>(url: string, data?: any) {
    showGlobalLoading();
    const log = new Tracker(host, project, logstore);
    const times = Date.now()
    const user = uni.getStorageSync('user')
    log.push('_url_', url);
    log.push('_userid_', user?.tenant_user_id);
    log.push('_name_', user?.name);
    log.push('_phone_', user?.phone);
    if (data) {
        log.push('_body_', JSON.stringify(data));
    }
    log.push('_type_', 'xiaochengxu')
    return new Promise<T>((res, rej) => {
        wx.cloud.callContainer({
            config: {
                env
            },
            path: url,
            header: {
                ...header
            },
            method: 'GET',
            data,
            success(r) {
                console.log(r)
                if (r.data.code === 1000) {
                    res(r.data.data)
                    return;
                }
                // 改进错误信息处理
                const errorMessage = r.data.message || r.data.msg || '请求失败'
                rej(errorMessage)
            },
            fail(f) {
                console.log(f)
                // 改进网络错误处理
                let errorMessage = '网络请求失败'
                if (f.data?.message) {
                    errorMessage = f.data.message
                } else if (f.data?.msg) {
                    errorMessage = f.data.msg
                } else if (f.errMsg) {
                    errorMessage = f.errMsg
                }
                rej(errorMessage)
            },
            complete(ccc) {
                const time = Date.now() - times
                log.push('_time_', time)
                log.push('_code_', ccc.data?.code)
                log.push('errMsg', ccc.errMsg)
                log.push('statusCode', ccc.statusCode)
                log.logger()
                hideGlobalLoading();
            }
        })
    })

}

const objsave = 'https://7072-prod-5g68x6an4c58cdc7-1321855978.tcb.qcloud.la/'


interface IFile {
    size: number
    thumb: string
    type: string
    url: string
}

export async function uploadFile(file: IFile, onCall: Function = () => { }): Promise<{ errMsg: string, fileID: string, statusCode: number, url: string, type: string, cover: string, size: number }> {
    showGlobalLoading();
    if (file.type === 'video') {
        return new Promise((resolve, reject) => {
            const path = 'file/' + dayjs().format('YYYY-MM-DD') + '/' + file.url.split('/').pop()
            const task = wx.cloud.uploadFile({
                cloudPath: path,
                filePath: file.url,
                config: {
                    env
                },
                success: res => {
                    const data = res
                    const _path = 'file/' + dayjs().format('YYYY-MM-DD') + '/' + file.thumb.split('/').pop()
                    const taskThumb = wx.cloud.uploadFile({
                        cloudPath: _path,
                        filePath: file.thumb,
                        config: {
                            env
                        },
                        success: thumbRes => {
                            hideGlobalLoading();
                            resolve({
                                ...data,
                                url: objsave + path,
                                cover: objsave + _path,
                                type: 'video',
                                size: file.size
                            })
                        },
                        fail: e => {
                            console.log(e)
                            const info = e.toString()
                            hideGlobalLoading();
                            if (info.indexOf('abort') != -1) {
                                reject(new Error('【文件上传失败】中断上传'))
                            } else {
                                reject(new Error('【文件上传失败】网络或其他错误'))
                            }
                        },
                    })
                    taskThumb.onProgressUpdate((resUpdate: any) => {
                        if (onCall(resUpdate) == false) {
                            taskThumb.abort()
                        }
                    })
                },
                fail: e => {
                    console.log(e)
                    const info = e.toString()
                    hideGlobalLoading();
                    if (info.indexOf('abort') != -1) {
                        reject(new Error('【文件上传失败】中断上传'))
                    } else {
                        reject(new Error('【文件上传失败】网络或其他错误'))
                    }
                },
            })
            task.onProgressUpdate((res: any) => {
                if (onCall(res) == false) {
                    task.abort()
                }
            })
        })
    }
    return new Promise((resolve, reject) => {
        const path = 'file/' + dayjs().format('YYYY-MM-DD') + '/' + file.url.split('/').pop()
        const task = wx.cloud.uploadFile({
            cloudPath: path,
            filePath: file.url,
            config: {
                env
            },
            success: res => {
                hideGlobalLoading();
                resolve({
                    ...res,
                    url: objsave + path,
                    cover: objsave + path,
                    type: file.type,
                    size: file.size
                })
            },
            fail: e => {
                console.log(e)
                const info = e.toString()
                hideGlobalLoading();
                if (info.indexOf('abort') != -1) {
                    reject(new Error('【文件上传失败】中断上传'))
                } else {
                    reject(new Error('【文件上传失败】网络或其他错误'))
                }
            },
        })
        task.onProgressUpdate((res: any) => {
            if (onCall(res) == false) {
                task.abort()
            }
        })
    })

}

// 导出强制隐藏loading的方法，以便在其他地方调用
export { forceHideLoading };

